package edu.yzu.testspringboot002.service.impl;

import cn.hutool.core.io.IoUtil;

import edu.yzu.testspringboot002.exception.BizException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * 上传服务
 *
 * @author yulang
 * @date 2023-11-27
 */
@Service
@Slf4j
public class UploadService {


    @Value("${minio.bucketName:edwin}")
    private String bucktName;

    @Autowired
    private MinioClient minioClient;


    @Value("${minio.jump-url:}")
    private String linkImageUrl;

    /**
     * 上传档案
     *
     * @param inputStream 输入流
     * @param objectSize  对象大小
     * @param partSize    零件尺寸  part size 3527 is not supported; minimum allowed 5MiB
     * @param objectName  对象名称
     * @return {@link String}
     */
    public String uploadFile(InputStream inputStream, long objectSize, String contentType,String objectName) {
        try {
            PutObjectArgs stream = PutObjectArgs.builder()
                    .bucket(bucktName).contentType(contentType)
                    .object(objectName)
                    .stream(inputStream, objectSize,0 ).build();
            minioClient.putObject(stream);
            return linkImageUrl.concat("/").concat(bucktName).concat("/").concat(objectName);
        } catch (Exception exception) {
            IoUtil.close(inputStream);
            log.error("文件上传失败：{}", exception.getLocalizedMessage());
            throw new BizException("文件上传失败！ ");
        }
    }
}
